<template>
    <el-dialog :title="dialogType == 'add' ? '新增用户' : '编辑用户'" v-model="dialogVisible" :before-close="handleClose"
        :close-on-click-modal="false" top="10vh" width="40%">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="所属机构:" prop="deptId">
                <el-tree-select v-model="form.deptId" node-key="id" :data="treeDept" :props="defaultTreeSelectProps"
                    filterable check-strictly clearable />
            </el-form-item>
            <el-form-item label="账号:" prop="username">
                <el-input v-model="form.username" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="名称:" prop="realName">
                <el-input v-model="form.realName" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="头像:" prop="headUrl">
                <el-input v-model="form.headUrl" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="性别:" prop="gender">
                <el-select v-model="form.gender" placeholder="请选择" clearable>
                    <el-option v-for="item in sexOptions" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="邮箱:" prop="email">
                <el-input v-model="form.email" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号:" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态:" prop="status">
                <el-switch v-model="form.status" active-text="正常" inactive-text="停用" active-value="1"
                    inactive-value="0" />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetClick()">重置</el-button>
            <el-button type="primary" :loading="btnLoading" @click="submitClick(formRef)">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { addUser, updateUser, getDeptSelectTree } from "@/api/sys/orgMemberApi";
import { ElMessage } from 'element-plus';
import { delNullProperty } from '@/utils';
import useAppStore from '@/stores/modules/app';

const sexOptions = computed(() => useAppStore().sysDict.sys_sex || []);

const defaultTreeSelectProps = {
    children: 'children',
    label: 'name',
}
const treeDept = ref<SysDeptEntity[]>([]);
const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
    deptId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    status: [{ required: true, message: '请输入状态', trigger: 'change' }],
})
const emit = defineEmits(['callback'])

const btnLoading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref('');
const form = ref({
    id: null,
    username: '',
    realName: '',
    headUrl: '',
    gender: '',
    email: '',
    mobile: '',
    deptId: null,
    status: '1'
})
const initTreeSelect = async () => {
    const res = await getDeptSelectTree();
    if (res.code == 200) {
        treeDept.value = res.result;
    }
}
const openLoad = (type: string, data: any) => {
    dialogVisible.value = true;
    dialogType.value = type;
    initTreeSelect()
    if (type == "add") {
        form.value.deptId = data.deptId;

    } else {
        form.value.id = data.id;
        form.value.deptId = data.deptId;
        form.value.username = data.username;
        form.value.realName = data.realName;
        form.value.headUrl = data.headUrl;
        form.value.gender = data.gender;
        form.value.email = data.email;
        form.value.mobile = data.mobile;
        form.value.status = data.status;
    }
}
const submitClick = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    btnLoading.value = true;
    setTimeout(() => {
        btnLoading.value = false;
    }, 5000);
    formEl.validate(async (valid) => {
        if (valid) {
            try {
                const data = {
                    ...delNullProperty(form.value)
                }
                const res = dialogType.value == 'add' ? await addUser(data) : await updateUser(data)
                if (res.code == 200) {
                    btnLoading.value = false;
                    dialogVisible.value = false;
                    ElMessage.success("操作成功！");
                    emit('callback')
                } else {
                    ElMessage.error(res.message);
                }
            } catch (error) {
                ElMessage.error("未知错误，请联系管理员！");
            }
        } else {
            console.log('error submit!')
            btnLoading.value = false
            return false;
        }
    })
}
const resetClick = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    } else {
        form.value.id = null;
        form.value.deptId = null;
        form.value.username = '';
        form.value.realName = '';
        form.value.headUrl = '';
        form.value.gender = '';
        form.value.email = '';
        form.value.mobile = '';
        form.value.status = '1';
    }

}
const handleClose = () => {
    resetClick();
    dialogType.value = '';
    dialogVisible.value = false;
    btnLoading.value = false;
}
defineExpose({
    openLoad
})
</script>